package com.linln.modules.capital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linln.modules.capital.repository.ShopCapitalMapper;
import com.linln.modules.capital.domain.ShopCapital;
import com.linln.modules.capital.service.ShopCapitalService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.modules.userule.service.impl
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.modules.userule.service.impl
 * @Description: TODO
 * @date Date : 2020年12月30日 10:46
 */

@Service
public class ShopCapitalServiceImpl extends ServiceImpl<ShopCapitalMapper, ShopCapital> implements ShopCapitalService {

    @Autowired
    private ShopCapitalMapper shopCapitalMapper;

    @Override
    public ShopCapital getShopCapitalByShopId(String shopId) {
        ShopCapital shopCapital = getShopCapital(shopId, null);
        if (shopCapital != null) {
            shopCapital.setDayProfit(0D);
            shopCapital.setMonthProfit(0D);
            return shopCapital;
        }
        return shopCapitalMapper.getInfoShopCapital(shopId);
    }

    @Override
    @Transactional
    public boolean addShopCapitalMoney(String shopId, Double money) {
        if (getShopCapital(shopId, money) != null) {
            return true;
        }
        //更新金额
        return shopCapitalMapper.addShopMoney(shopId, money);
    }


    @Override
    public boolean updateShopCapital(ShopCapital shopCapital) {
        return this.updateById(shopCapital);
    }

    //获取店铺资金 如果没有创建
    private ShopCapital getShopCapital(String shopId, Double initialMoney) {
        ShopCapital capital = this.getOne(new QueryWrapper<ShopCapital>().eq("shop_id", shopId));
        if (capital == null) {
            initialMoney = Optional.ofNullable(initialMoney).orElse(0D);
            ShopCapital shopCapital = new ShopCapital();
            shopCapital.setShopId(shopId);
            shopCapital.setAvailableAmount(initialMoney);
            shopCapital.setTotalAmount(initialMoney);
            shopCapital.setFrozenAmount(0D);
            this.save(shopCapital);
            return shopCapital;
        }
        return null;
    }
}
